import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import { STORAGE_KEYS, USER_TYPES } from '@/utils/constants'

// 添加一个函数来从存储中恢复状态
function restoreStateFromStorage() {
  console.log('尝试从存储中恢复状态')
  const token = localStorage.getItem(STORAGE_KEYS.TOKEN) || sessionStorage.getItem(STORAGE_KEYS.TOKEN)
  let userInfo = null
  
  try {
    const userInfoStr = localStorage.getItem(STORAGE_KEYS.USER_INFO) || sessionStorage.getItem(STORAGE_KEYS.USER_INFO)
    if (userInfoStr) {
      userInfo = JSON.parse(userInfoStr)
    }
  } catch (e) {
    console.error('解析用户信息失败:', e)
  }
  
  console.log('从存储恢复的状态:', { token, userInfo })
  return { token, userInfo }
}

// 在store定义之外就尝试恢复状态
const { token: initialToken, userInfo: initialUserInfo } = restoreStateFromStorage()

export const useUserStore = defineStore('user', () => {
  // 添加调试信息
  console.log('UserStore 初始化前的本地存储状态:', {
    localStorageToken: localStorage.getItem('graduation_check_token'),
    localStorageUserInfo: localStorage.getItem('graduation_check_user_info'),
    sessionStorageToken: sessionStorage.getItem('graduation_check_token'),
    sessionStorageUserInfo: sessionStorage.getItem('graduation_check_user_info'),
    localStorageKeys: Object.keys(localStorage),
    sessionStorageKeys: Object.keys(sessionStorage)
  })
  
  // 状态 - 优先从本地存储初始化
  const token = ref(initialToken)
  const userInfo = ref(initialUserInfo)
  
  console.log('UserStore 初始化:', {
    hasToken: !!token.value,
    hasUserInfo: !!userInfo.value,
    userType: userInfo.value?.userType,
    tokenValue: token.value,
    userInfoValue: userInfo.value
  })
  
  // 计算属性
  const isLoggedIn = computed(() => {
    const result = !!token.value && token.value.length > 0 && !!userInfo.value
    console.log('计算 isLoggedIn:', {
      token: !!token.value,
      tokenLength: token.value ? token.value.length : 0,
      userInfo: !!userInfo.value,
      result
    })
    return result
  })
  const isStudent = computed(() => userInfo.value?.userType === USER_TYPES.STUDENT)
  const isTeacher = computed(() => userInfo.value?.userType === USER_TYPES.TEACHER)
  const userName = computed(() => userInfo.value?.name || '')
  const userAccount = computed(() => userInfo.value?.account || '')
  const userClass = computed(() => userInfo.value?.className || '')
  const userMajor = computed(() => userInfo.value?.major || '')
  
  // 登录方法
  function login(loginToken, user) {
    console.log('开始保存登录状态:', {
      token: loginToken ? `${loginToken.substring(0, 20)}...` : '无token',
      userType: user?.userType,
      account: user?.account
    })
    
    token.value = loginToken
    userInfo.value = user
    
    // 使用双重保存机制：同时保存到 localStorage 和 sessionStorage
    if (loginToken && loginToken.length > 0 && user) {
      console.log('准备保存到存储:', {
        tokenLength: loginToken.length,
        hasUserInfo: !!user
      })
      
      // 保存到 localStorage（持久化）
      localStorage.setItem(STORAGE_KEYS.TOKEN, loginToken)
      localStorage.setItem(STORAGE_KEYS.USER_INFO, JSON.stringify(user))
      
      // 同时保存到 sessionStorage（备份）
      sessionStorage.setItem(STORAGE_KEYS.TOKEN, loginToken)
      sessionStorage.setItem(STORAGE_KEYS.USER_INFO, JSON.stringify(user))
      
      console.log('登录信息已保存到 localStorage 和 sessionStorage')
      console.log('保存后的存储状态:', {
        localStorageToken: localStorage.getItem(STORAGE_KEYS.TOKEN),
        localStorageUserInfo: localStorage.getItem(STORAGE_KEYS.USER_INFO),
        sessionStorageToken: sessionStorage.getItem(STORAGE_KEYS.TOKEN),
        sessionStorageUserInfo: sessionStorage.getItem(STORAGE_KEYS.USER_INFO)
      })
    }
    
    console.log('登录状态已更新:', {
      token: loginToken ? `${loginToken.substring(0, 10)}...` : '无token',
      userType: user?.userType,
      isLoggedIn: !!loginToken && !!user
    })
  }
  
  // 登出方法
  function logout() {
    token.value = ''
    userInfo.value = null
    
    // 清除本地存储
    localStorage.removeItem(STORAGE_KEYS.TOKEN)
    localStorage.removeItem(STORAGE_KEYS.USER_INFO)
    sessionStorage.removeItem(STORAGE_KEYS.TOKEN)
    sessionStorage.removeItem(STORAGE_KEYS.USER_INFO)
    
    console.log('已登出并清除所有存储')
  }
  
  // 浏览器关闭时清除数据
  function clearOnBrowserClose() {
    console.log('浏览器关闭，清除登录数据')
    
    // 清除状态
    token.value = ''
    userInfo.value = null
    
    // 清除所有存储中的用户相关数据
    localStorage.removeItem(STORAGE_KEYS.TOKEN)
    localStorage.removeItem(STORAGE_KEYS.USER_INFO)
    sessionStorage.removeItem(STORAGE_KEYS.TOKEN)
    sessionStorage.removeItem(STORAGE_KEYS.USER_INFO)
    
    console.log('浏览器关闭数据清除完成')
  }
  
  // 更新用户信息
  function updateUserInfo(newUserInfo) {
    userInfo.value = { ...userInfo.value, ...newUserInfo }
    localStorage.setItem(STORAGE_KEYS.USER_INFO, JSON.stringify(userInfo.value))
    sessionStorage.setItem(STORAGE_KEYS.USER_INFO, JSON.stringify(userInfo.value))
  }
  
  // 记住账号
  function rememberAccount(account) {
    if (account) {
      localStorage.setItem(STORAGE_KEYS.REMEMBER_ACCOUNT, account)
    } else {
      localStorage.removeItem(STORAGE_KEYS.REMEMBER_ACCOUNT)
    }
  }
  
  // 获取记住的账号
  function getRememberedAccount() {
    return localStorage.getItem(STORAGE_KEYS.REMEMBER_ACCOUNT) || ''
  }
  
  // 获取当前token（提供外部访问方法）
  function getToken() {
    return token.value
  }
  
  // 手动恢复状态方法
  function restoreState() {
    const { token: restoredToken, userInfo: restoredUserInfo } = restoreStateFromStorage()
    // 检查是否有有效的token和userInfo
    if (restoredToken && restoredToken.length > 0 && restoredUserInfo) {
      token.value = restoredToken
      userInfo.value = restoredUserInfo
      console.log('手动恢复状态成功')
      return true
    }
    console.log('手动恢复状态失败，无有效数据')
    return false
  }
  
  // 强制检查并恢复状态
  function forceRestoreState() {
    console.log('强制检查并恢复状态')
    const { token: restoredToken, userInfo: restoredUserInfo } = restoreStateFromStorage()
    console.log('强制恢复检查结果:', { restoredToken, restoredUserInfo })
    
    // 检查是否有有效的token和userInfo
    if (restoredToken && restoredToken.length > 0 && restoredUserInfo) {
      token.value = restoredToken
      userInfo.value = restoredUserInfo
      console.log('强制恢复状态成功')
      return true
    }
    
    console.log('强制恢复状态失败，无有效数据')
    return false
  }
  
  // 监听token和userInfo的变化，同步到存储
  watch([token, userInfo], ([newToken, newUserInfo]) => {
    console.log('用户状态发生变化:', { newToken, newUserInfo })
    if (newToken && newToken.length > 0 && newUserInfo) {
      localStorage.setItem(STORAGE_KEYS.TOKEN, newToken)
      localStorage.setItem(STORAGE_KEYS.USER_INFO, JSON.stringify(newUserInfo))
      sessionStorage.setItem(STORAGE_KEYS.TOKEN, newToken)
      sessionStorage.setItem(STORAGE_KEYS.USER_INFO, JSON.stringify(newUserInfo))
    }
  }, { deep: true })
  
  return {
    // 状态
    token,
    userInfo,
    
    // 计算属性
    isLoggedIn,
    isStudent,
    isTeacher,
    userName,
    userAccount,
    userClass,
    userMajor,
    
    // 方法
    login,
    logout,
    clearOnBrowserClose,
    updateUserInfo,
    rememberAccount,
    getRememberedAccount,
    getToken,
    restoreState,
    forceRestoreState
  }
})